﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using University.Workshop.Presentation.Users;
using System.Net;
using System.Net.Sockets;



namespace University.Workshop.Presentation
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        Login welcomePage;
        ChangePassword changePassword;

        public static string idUsuarioActivo;
        public static Model.User userActive;

        public MainWindow()
        {
            InitializeComponent();
            welcomePage = new Login(this);

            //frmContent.Navigate(welcomePage);
            frmContent.Navigate(welcomePage);

            LoadBackGround();
            


        }

        public void LoadBackGround()
        {
            try
            {
                ICollection<Model.OtbData> otbData = University.Workshop.DataAccess.DataAccessOtbData.GetCurrentOtbData();
                if (otbData.Count > 0)
                {
                    string path = otbData.First().Background;
                    string name = otbData.First().Name;
                    if (path != string.Empty)
                    {
                        ImageBrush myBrush = new ImageBrush();
                        myBrush.ImageSource =
                            new BitmapImage(new Uri(path, UriKind.Absolute));
                        this.ContentPageGrid.Background = myBrush;
                        //this.frmContent.Background = myBrush;
                    }
                    OtbNameLbl.Text = name;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void ChangeBackground(object sender, string newBackgroundPath, string otbName)
        {
            if (newBackgroundPath != string.Empty)
            {
                Uri pathUri = new Uri(newBackgroundPath);
                BitmapImage image = new BitmapImage(pathUri);
                ContentPageGrid.Background = new ImageBrush(image);
            }
            else
            { 
                ContentPageGrid.Background = null;
            }
            OtbNameLbl.Text = otbName;
            //frmContent.Background = new ImageBrush(image);
        }
        #region TreeView Folding
        private void TreeViewItem_Selected(object sender, RoutedEventArgs e)
        {
            TreeViewItem tvi = (TreeViewItem)e.OriginalSource;
            TreeView menu = (TreeView)sender;
            if (tvi != null)
            {
                tvi.IsExpanded = !tvi.IsExpanded;
            }

            foreach (TreeViewItem item in menu.Items)
            {
                if (item.Header != tvi.Header)
                    CollapseTreeViewItem(item, tvi);
            }

            /////////////////////////////
            //var tv = sender as TreeView;

            //if (tv != null)
            //{
            //    var item = (TreeViewItem)tv.SelectedItem;
            //    item.IsSelected = false;
            //    tv.Focus();
            //}        
        }

        void CollapseTreeViewItem(TreeViewItem item,TreeViewItem selected)
        {
            if(item.Header != selected.Header)
                item.IsExpanded = false;

            foreach (TreeViewItem subitem in item.Items)
            {
                CollapseTreeViewItem(subitem,selected);
            }
        }

        #endregion

        #region TreeView Options
        private void SearchKardexSelected(object sender, RoutedEventArgs e)
        {
            frmContent.Navigate(new Kardex.SearchKardex());
        }

        private void RegisterKardexSelected(object sender, RoutedEventArgs e)
        {
            frmContent.Navigate(new Kardex.Register.PageRegisterView());
        }


        private void SearchPersonSelected(object sender, RoutedEventArgs e)
        {
            frmContent.Navigate(new Person.SearchPerson());
        }

        private void SearchCisternSelected(object sender, RoutedEventArgs e)
        {
            frmContent.Navigate(new Cistern.SearchCistern());
        }

        private void RegisterCisternSelected(object sender, RoutedEventArgs e)
        {
            frmContent.Navigate(new Cistern.Register.RegisterCisternPrincipalData());
        }

        private void SearchUserSelected(object sender, RoutedEventArgs e)
        {
            frmContent.Navigate(new Users.SearchUser());
        }

        private void RegisterUserSelected(object sender, RoutedEventArgs e)
        {
            frmContent.Navigate(new Users.Register.PageRegisterView());
        }

        private void ChangePasswordUserSelected(object sender, RoutedEventArgs e)
        {
            frmContent.Navigate(new Users.ChangePassword(userActive, this));
        }

        private void RegisterSquareSelected(object sender, RoutedEventArgs e)
        {
            frmContent.Navigate(new Square.Register.PageRegisterView());
        }

        private void SearchSquareSelected(object sender, RoutedEventArgs e)
        {
            frmContent.Navigate(new Square.SearchSquare());
        }

        private void RegisterOtbDataSelected(object sender, RoutedEventArgs e)
        {
            //configurationView.ChangeBackground = new ChangeBackgroundEventHandler(this.ChangeBackground);
            frmContent.Navigate(new OTBData.Register.RegisterOtbDataPrincipal() { ChangeBackground = new OTBData.Register.ChangeBackgroundEventHandler(this.ChangeBackground)});
        }

        private void ModifyOtbDataSelected(object sender, RoutedEventArgs e)
        {
            frmContent.Navigate(new OTBData.Modify.ModifyOtbDataPrincipal() { ChangeBackground = new OTBData.Modify.ChangeBackgroundEventHandler(this.ChangeBackground) });   
        }

        private void SearchOtbDataSelected(object sender, RoutedEventArgs e)
        {
            frmContent.Navigate(new OTBData.SearchOtbData());   
        }

        private void RegisterFeesAndFines(object sender, RoutedEventArgs e)
        {
            frmContent.Navigate(new FeesAndFines.RegisterFees());
        }
        private void ModifyFeesAndFines(object sender, RoutedEventArgs e)
        {
            frmContent.Navigate(new FeesAndFines.ModifyFees());
        }
        private void SearchFeesAndFines(object sender, RoutedEventArgs e)
        {
            frmContent.Navigate(new FeesAndFines.SearchFees());
        }

        private void SearchWaterPurchaseSelected(object sender, RoutedEventArgs e)
        {
            frmContent.Navigate(new WaterPurchase.SearchWaterPurchase());
        }

        private void RegisterWaterPurchaseSelected(object sender, RoutedEventArgs e)
        {
            frmContent.Navigate(new WaterPurchase.PageRegisterView());
        }

        private void SearchExpenseSelected(object sender, RoutedEventArgs e)
        {
            frmContent.Navigate(new Expenses.SearchExpense());
        }

        private void RegisterExpenseSelected(object sender, RoutedEventArgs e)
        {
            frmContent.Navigate(new Register(userActive, this));
        }

        private void SearchOutflowSelected(object sender, RoutedEventArgs e)
        {
            frmContent.Navigate(new OutflowMoney.SearchOutFlow());
        }

        private void SearchIncomeSelected(object sender, RoutedEventArgs e)
        {
            frmContent.Navigate(new IncomeMoney.SearchIncome());
        }

        private void SearchIncomeVsOutflowSelected(object sender, RoutedEventArgs e)
        {
            frmContent.Navigate(new IncomeVsOutflow.SearchIncomeVsOutFlow());
        }

        private void RegisterOtherCollectControl(object sender, RoutedEventArgs e)
        {
            frmContent.Navigate(new CollectControl.OtherCollectControlRegister());
        }
        
        private void RegisterFineCollectColtrol(object sender, RoutedEventArgs e)
        {
            frmContent.Navigate(new CollectControl.FineCollectControlRegister());
        }

        private void SearchCollectControlSelected(object sender, RoutedEventArgs e)
        {
            frmContent.Navigate(new CollectControl.SearchPayments());
        }

        private void MakeCollectControlPending(object sender, RoutedEventArgs e)
        {
            frmContent.Navigate(new CollectControl.RegisterPayment(userActive));
        }

        private void GetCurrentIp(object sender, RoutedEventArgs e)
        {
            string ip = GetIpWifi();
            if (ip == "?")
            {
                MessageBox.Show(App.Current.MainWindow, "No existe conexion a ninguna red", "Error!!!", MessageBoxButton.OK, MessageBoxImage.Error, MessageBoxResult.OK, MessageBoxOptions.RightAlign);
            }
            else
            {
                MessageBox.Show(App.Current.MainWindow, "IP: " + ip, "", MessageBoxButton.OK, MessageBoxImage.Information, MessageBoxResult.OK, MessageBoxOptions.RightAlign);
            }
        }

        private void RegisterChangeWaterMeassure(object sender, RoutedEventArgs e)
        {
            frmContent.Navigate(new WaterReading.SearchKardexMeasure());   
        }

        private void PendingWaterReadings(object sender, RoutedEventArgs e)
        {
            frmContent.Navigate(new WaterReading.SearchWaterReading());
        }

        private void ActivateGenerator(object sender, RoutedEventArgs e)
        {
            //getting current OTB data
            ICollection<Model.OtbData> otbs = DataAccess.DataAccessOtbData.GetCurrentOtbData();
            if (otbs.Count == 0)
            {
                MessageBox.Show(App.Current.MainWindow, "No existen datos de OTB registrados sera redireccionado al registro", "Error!!!", MessageBoxButton.OK, MessageBoxImage.Error, MessageBoxResult.OK, MessageBoxOptions.RightAlign);
                frmContent.Navigate(new OTBData.Register.RegisterOtbDataPrincipal() { ChangeBackground = new OTBData.Register.ChangeBackgroundEventHandler(this.ChangeBackground) });
                //frmContent.Navigate(new OTBData.Register.RegisterOtbDataPrincipal());
                return;
            }
            //-------------------------------------------------------------------------//
            
            //getting current fees and fines
            ICollection<Model.FeesAndFines> p = DataAccess.DataAccessFeesAndFines.GetLastInserted();
            if (p.Count == 0)
            {
                MessageBox.Show(App.Current.MainWindow, "No Existen tarifas registradas sera redireccionado al Registro", "Error!!!", MessageBoxButton.OK, MessageBoxImage.Error, MessageBoxResult.OK, MessageBoxOptions.RightAlign);
                frmContent.NavigationService.Navigate(new FeesAndFines.RegisterFees());
                return;
            }
            //-------------------------------------------------------------------------//
            
            MessageBoxResult result = MessageBox.Show(App.Current.MainWindow, "Debe registrar previamente todos los medidores, Esta seguro que desea activar el generador", "", MessageBoxButton.YesNo, MessageBoxImage.Warning, MessageBoxResult.Yes, MessageBoxOptions.None);
            if (result == MessageBoxResult.Yes)
            {
                Model.AppConfiguration config = new Model.AppConfiguration() { FlagSync = true };
                DataAccess.DataAccessConfiguration.Insert(config);
                System.Windows.Forms.Application.Restart();
                System.Windows.Application.Current.Shutdown();
            }

        }
        #endregion

        public string GetIpWifi()
        {
            IPHostEntry host;
            string localIP = "?";
            host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (IPAddress ip in host.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    localIP = ip.ToString();
                }
            }
            return localIP;
        }

        public void salirSistema()
        {
            //welcomePage.Visibility = System.Windows.Visibility.Visible;
            
            //frmContent.Navigate(welcomePage);
            frmContent.Navigate(new Login(this));

            Usuarios.Visibility = System.Windows.Visibility.Hidden;
            Kardex.Visibility = System.Windows.Visibility.Hidden;
            Personas.Visibility = System.Windows.Visibility.Hidden;
            Cisternas.Visibility = System.Windows.Visibility.Hidden;
            Manzanos.Visibility = System.Windows.Visibility.Hidden;
            Egresos.Visibility = System.Windows.Visibility.Hidden;
            Compra.Visibility = System.Windows.Visibility.Hidden;
            LecturaAgua.Visibility = System.Windows.Visibility.Hidden;
            Servicios.Visibility = System.Windows.Visibility.Hidden;
            Configuraciones.Visibility = System.Windows.Visibility.Hidden;
            Cobro.Visibility = System.Windows.Visibility.Hidden;
            WaterForPeople.Visibility = System.Windows.Visibility.Hidden;
            ActivarGenerador.Visibility = System.Windows.Visibility.Hidden;

            Salir.Visibility = System.Windows.Visibility.Hidden;
        }

        private void SalirSelected(object sender, RoutedEventArgs e)
        {
            salirSistema();
        }

        public void cambiarPassword(Model.User user)
        {
            App.Current.MainWindow.Title = "Sistema de Gestión de Pagos y Cobros de Agua";
            //idUsuarioActivo = user.UserId;
            //changePassword = 
            Salir.Visibility = System.Windows.Visibility.Visible;

            frmContent.Navigate(new Users.ChangePassword(user,this));
            user = null;
        }

        public void mostrarMenus(Model.User user)
        {
            App.Current.MainWindow.Title = "Sistema de Gestión de Pagos y Cobros de Agua";
            idUsuarioActivo = user.UserId;
            userActive = user;

            switch (user.Role)
            {
                case 0: // "Administrador";

                    Usuarios.Visibility = System.Windows.Visibility.Visible;
                    Kardex.Visibility = System.Windows.Visibility.Visible;
                    Personas.Visibility = System.Windows.Visibility.Visible;
                    Cisternas.Visibility = System.Windows.Visibility.Visible;
                    Manzanos.Visibility = System.Windows.Visibility.Visible;
                    Egresos.Visibility = System.Windows.Visibility.Visible;
                    Compra.Visibility = System.Windows.Visibility.Visible;
                    LecturaAgua.Visibility = System.Windows.Visibility.Visible;
                    Servicios.Visibility = System.Windows.Visibility.Visible;
                    Configuraciones.Visibility = System.Windows.Visibility.Visible;
                    Cobro.Visibility = System.Windows.Visibility.Visible;
                    //Seguimiento WFP
                    WaterForPeople.Visibility = System.Windows.Visibility.Visible;
                    ActivarGenerador.Visibility = System.Windows.Visibility.Visible;

                    Salir.Visibility = System.Windows.Visibility.Visible;
                    //------------------------------------------------------------------
                    
                    ICollection<Model.AppConfiguration> config = DataAccess.DataAccessConfiguration.GetCurrent();
                    if (config.Count != 0)
                    {
                        Model.AppConfiguration c = config.First();
                        if (c.FlagSync)
                            ActivarGenerador.Visibility = System.Windows.Visibility.Hidden;
                    }
                    //------------------------------------------------------------------
                    break;

                case 1: //"Operador";
                    Cobro.Visibility = Visibility.Visible;
                    Egresos.Visibility = Visibility.Visible;
                    Compra.Visibility = Visibility.Visible;
                    Kardex.Visibility = Visibility.Visible;
                    Servicios.Visibility = Visibility.Visible;

                    Salir.Visibility = Visibility.Visible;
                    break;

                case 2: //"Presidente";
                    Usuarios.Visibility = Visibility.Visible;
                    Configuraciones.Visibility = Visibility.Visible;
                    Cisternas.Visibility = Visibility.Visible;
                    Manzanos.Visibility = Visibility.Visible;
                    //Asistencia a reuniones

                    Salir.Visibility = Visibility.Visible;
                    break;

                case 3: //"Cajero"; o tesorero
                    Cobro.Visibility = Visibility.Visible;
                    Egresos.Visibility = Visibility.Visible;
                    Compra.Visibility = Visibility.Visible;

                    Salir.Visibility = Visibility.Visible;
                    break;
                   
              /*case 4: //Encargado de lectura
                    Lectura.Visibility = Visibility.Visible;

                    Salir.Visibility = Visibility.Visible;
                    break;*/
            }

            user = null;
        }

        public void verificarMultas()
        {
            //if (DateTime.Now.Day > 15)
            //    /MessageBox.Show("Hola man");
                
        }

        private void BackUpSelected(object sender, RoutedEventArgs e)
        {
            frmContent.Navigate(new BackUp.BackUp());
        }


    }
}
